package com.orange.lockscreensettings.wallpaper;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher.ViewFactory;

import com.orange.lockscreensettings.R;
import com.orange.lockscreensettings.common.Constants;
import com.orange.lockscreensettings.common.LogHelper;
import com.orange.lockscreensettings.common.SettingsUtils;

public class WallpaperActivity extends Activity implements ViewFactory,
		OnClickListener {
	public static final String		TAG					= "WallpaperActivity";

	private static final String[]	BACKGROUND_NAMES	= {
			"wallpaper_bubbles", "wallpaper_circles", "wallpaper_stripes",
			"wallpaper_candles", "wallpaper_3d_lights"					};

	private List<Integer>			BACKGROUND_ID;

	private Resources				mOtherAppResources	= null;

	private ImageSwitcher			mImageSwitcher;
	private int						mWallpaperIndex		= 0;
	private WallpaperLoader			mLoader;
	private Bitmap					mBitmap;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		findWallpapers();
		if (BACKGROUND_ID == null || BACKGROUND_ID.isEmpty()) {
			this.finish();
			return;
		}

		setContentView(R.layout.wallpaper);

		mImageSwitcher = (ImageSwitcher) findViewById(R.id.switcher);
		mImageSwitcher.setFactory(this);
		mImageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
				android.R.anim.fade_in));
		mImageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
				android.R.anim.fade_out));

		mWallpaperIndex = SettingsUtils.getIndexOfBG();

		Gallery gallery = (Gallery) findViewById(R.id.gallery);
		gallery.setAdapter(new ImageAdapter(this));
		gallery.setCallbackDuringFling(false);

		gallery.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {

				if (mLoader != null
						&& mLoader.getStatus() != WallpaperLoader.Status.FINISHED) {
					mLoader.cancel();
				}

				mLoader = (WallpaperLoader) new WallpaperLoader()
						.execute(position);

				mWallpaperIndex = position;

			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		});

		Button button = (Button) findViewById(R.id.set_wallpaper);
		button.setOnClickListener(this);

		gallery.setSelection(mWallpaperIndex);

	}

	private void findWallpapers() {
		try {
			Context otherAppContext = this.createPackageContext(
					Constants.PKG_LOCKSCREEN, Context.CONTEXT_IGNORE_SECURITY);
			if (null != otherAppContext) {
				mOtherAppResources = otherAppContext.getResources();
				if (null != mOtherAppResources) {
					BACKGROUND_ID = new ArrayList<Integer>(
							BACKGROUND_NAMES.length);
					for (int i = 0; i < BACKGROUND_NAMES.length; i++) {
						int id = mOtherAppResources.getIdentifier(
								BACKGROUND_NAMES[i], "drawable",
								Constants.PKG_LOCKSCREEN);

						LogHelper.v(TAG, "findWallpapers. id=" + id);
						BACKGROUND_ID.add(id);
					}
				}
			}
		} catch (NameNotFoundException e) {
		}
	}

	public View makeView() {
		ImageView imageView = new ImageView(this);
		imageView.setBackgroundColor(0xFF000000);
		imageView.setScaleType(ImageView.ScaleType.FIT_XY);
		imageView.setLayoutParams(new ImageSwitcher.LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		return imageView;
	}

	@Override
	protected void onDestroy() {
		if (mLoader != null
				&& mLoader.getStatus() != WallpaperLoader.Status.FINISHED) {
			mLoader.cancel(true);
			mLoader = null;
		}
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		if (mWallpaperIndex != SettingsUtils.getIndexOfBG()
				|| SettingsUtils.isWallpaperFromGallery()) {
			SettingsUtils.setIndexOfBG(mWallpaperIndex);
			setResult(RESULT_OK);
		}
		this.finish();
	}

	public class ImageAdapter extends BaseAdapter {
		private Context	context;
		private int		itemBackground;

		public ImageAdapter(Context c) {
			super();

			context = c;
			TypedArray a = obtainStyledAttributes(R.styleable.GallerySelect);
			itemBackground = a.getResourceId(
					R.styleable.GallerySelect_android_galleryItemBackground, 0);
			a.recycle();
		}

		public int getCount() {
			return BACKGROUND_NAMES.length;
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView imageView = new ImageView(context);
			Drawable drawable = mOtherAppResources.getDrawable(BACKGROUND_ID
					.get(position));
			imageView.setImageDrawable(drawable);
			imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
			imageView.setLayoutParams(new Gallery.LayoutParams(240, 180));
			imageView.setBackgroundResource(itemBackground);
			return imageView;
		}
	}

	class WallpaperLoader extends AsyncTask<Integer, Void, Bitmap> {
		BitmapFactory.Options	mOptions;

		WallpaperLoader() {
			super();
			mOptions = new BitmapFactory.Options();
			mOptions.inDither = false;
			mOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
		}

		protected Bitmap doInBackground(Integer... params) {
			if (isCancelled())
				return null;
			try {
				return BitmapFactory.decodeResource(mOtherAppResources,
						BACKGROUND_ID.get(params[0]), mOptions);
			} catch (OutOfMemoryError e) {
				return null;
			}
		}

		@Override
		protected void onPostExecute(Bitmap b) {
			if (b == null)
				return;

			if (!isCancelled() && !mOptions.mCancel) {

				final ImageSwitcher view = mImageSwitcher;
				view.setImageDrawable(null);
				if (mBitmap != null) {
					mBitmap.recycle();
				}
				view.setImageDrawable(new BitmapDrawable(b));

				mBitmap = b;

				view.postInvalidate();

				mLoader = null;
			} else {
				b.recycle();
			}
		}

		void cancel() {
			mOptions.requestCancelDecode();
			super.cancel(true);
		}
	}
}
